from odoo import api, fields, models
from odoo.exceptions import UserError
from ..primary.rp_customer_coupon import COUPON_TYPE
from ..primary.rp_marketing_coupon_template import DISCOUNT_ELIGIBILITY


class RpAvailableCustomerCouponTran(models.TransientModel):
    _name = 'rp.available.customer.coupon.tran'
    _description = '客户可用优惠券'

    # 基本信息
    name = fields.Char(string='名称', required=True, copy=False)
    code = fields.Char(string='序列号', required=True, copy=False)
    par_value = fields.Float(string='面值', copy=False)
    discount_value = fields.Float(string='折扣', copy=False)
    is_stacked = fields.Boolean(string='叠加', copy=False)
    rp_customer_coupon_id = fields.Many2one(string='客户优惠券', comodel_name='rp.customer.coupon', required=True, copy=False)
    coupon_type = fields.Selection(string='优惠券类型', selection=COUPON_TYPE, copy=False)

    # 优惠信息
    coupon_for = fields.Selection(string='优惠对象', selection=DISCOUNT_ELIGIBILITY, required=True, copy=False)
    rp_coupon_mail_route_id = fields.Many2one(string='单一邮路', comodel_name='rp.shipper.mail.route', copy=False)
    rp_coupon_valued_added_id = fields.Many2one(string='增值服务', comodel_name='rp.shipper.sale.template.value.added.line', copy=False)

    def action_rewrite_coupon_line(self):
        records = self.browse(self.env.context.get('active_ids'))
        # 校验规则
        self.validity_function(records)
        ship_order = self.env['rp.ship.order'].browse(self.env.context.get('ship_order_id'))
        # 查询已经添加过的优惠券
        retrieved_available_coupon_ids = ship_order.rp_shipper_order_coupon_line_ids.mapped('rp_customer_coupon_id')

        value_added_list = []
        for record in records:
            if record.rp_customer_coupon_id.id not in retrieved_available_coupon_ids.ids:
                value_added_value = {
                    'name': record.name,
                    'code': record.code,
                    'par_value': record.par_value,
                    'discount_value': record.discount_value,
                    'rp_customer_coupon_id': record.rp_customer_coupon_id.id if record.rp_customer_coupon_id else False,
                    'coupon_for': record.coupon_for,
                    'coupon_type': record.coupon_type,
                    'rp_coupon_mail_route_id': record.rp_coupon_mail_route_id.id,
                    'rp_coupon_valued_added_id': record.rp_coupon_valued_added_id.id if record.rp_coupon_valued_added_id else False,
                }
                value_added_list.append((0, 0, value_added_value))
        ship_order.write({'rp_shipper_order_coupon_line_ids': value_added_list, 'rp_shipper_order_coupon_flag': True, 'coupon_select_tag': True})

    def validity_function(self, records):
        """
        折扣券和折扣券(两者需要同时可叠加)，以和的形式进行折扣
        折扣券和满减券，以满减券先进行计算
        """
        # 全免券校验
        amount_for_completely_free = records.filtered(lambda r: r.coupon_type == 'free_charge')
        for record in amount_for_completely_free:
            #  相同类型下全免+全免，全免+折扣，全免+满减不符合规则
            search_result = records.filtered(lambda r: all([r.coupon_for == record.coupon_for, r.rp_coupon_mail_route_id.id == record.rp_coupon_mail_route_id.id, r.rp_coupon_valued_added_id.id == record.rp_coupon_valued_added_id.id]))
            if len(search_result) > 1:
                raise UserError('同一情况下全免券若已选取，不可以选取其他类型的优惠券！')
        # 叠加校验(适用于满减券和折扣券）
        amount_for_not_stacked = records.filtered(lambda r: r.coupon_type != 'free_charge' and r.is_stacked is False)
        for record in amount_for_not_stacked:
            search_result = records.filtered(lambda r: all([r.coupon_type == record.coupon_type and r.coupon_for == record.coupon_for, r.rp_coupon_mail_route_id.id == record.rp_coupon_mail_route_id.id, r.rp_coupon_valued_added_id.id == record.rp_coupon_valued_added_id.id]))
            if len(search_result) > 1:
                raise UserError('相同条件下，您同时选择了可叠加和不可叠加的优惠券！')
